package com.itheima.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class TxAdvice {

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Object transactionManager(ProceedingJoinPoint pjp) throws Throwable {

        System.out.println("......");
        DataSourceTransactionManager dstm = new DataSourceTransactionManager();
        TransactionStatus ts;
        //创建事务管理器
        //为事务管理器设置与数据源相同的数据源
        dstm.setDataSource(dataSource);
        //创建事务定义对象
        DefaultTransactionDefinition td = new DefaultTransactionDefinition();
        //创建事务状态对象,用于控制事务执行
        ts = dstm.getTransaction(td);
        Object proceed = null;
        try {
            //
            proceed = pjp.proceed();
            //
            //提交事务
            dstm.commit(ts);
        } catch (Exception e) {
            e.printStackTrace();
            dstm.rollback(ts);
        } finally {

        }
        System.out.println("......");
        return proceed;
    }

}
